<?php


namespace biu\lib;

use \biu\Biu;
use biu\model\LogModel;

class Log
{

    const LEVEL_ERR = 1;
    const LEVEL_SQL = 2;
    const LEVEL_WARN = 3;
    const LEVEL_INFO = 4;
    const LEVEL_DEBUG = 5;


    private static $logs = [];
    public static function info($content,$catlog=''){
        self::export('info',$content,$catlog);
    }
    public static function err($content,$catlog=''){
        self::export('err',$content,$catlog);
    }

    public static function flush(){

        if(empty(self::$logs)) return;
        $log_level = Conf::file('log_level');
        foreach (self::$logs as /** @var $log LogModel */ $log){
            $level = $log->getLevel();
            if($level > $log_level) continue;
            $dir = $log->getDir();
            file_exists($dir) or mkdir($dir,777,true);
            file_put_contents($dir.$log->getFile(),$log->getStr().PHP_EOL,FILE_APPEND|LOCK_EX);
        }
    }

    private static function export($level,$content,$catlog=''){
        #debug_print_backtrace();die;
        $caller = debug_backtrace()[1];
        $file = str_replace(HOME,'',$caller['file']);
        #print_r($caller);
        #die($caller['file'].PHP_EOL.HOME);
        empty($catlog) and $catlog = str_replace(DIRECTORY_SEPARATOR,'_',$file);

        $time = date('Y-m-d H:i:s');
        $str = $time."\t".$level."\t".$file.':'.$caller['line']."\t";
        if (is_scalar($content))
            $str .= $content;
        elseif (is_null($content))
            $str .= 'null';
        elseif (is_array($content))
            $str .= json_encode($content);
            #$str .= json_encode($content,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
        elseif (is_object($content))
            $str .= get_class($content)."\t".json_encode($content);
        else
            $str .= 'no data type for ： '.gettype($content);


        if('cli' == PHP_SAPI){
            echo $str.PHP_EOL;
        }else{
            header('log-'.microtime(1).':'.$str);
            $str .= json_encode($_REQUEST);
        }

        $dir = HOME.'run/'.PROJECT.date('/Y/m/d/');
        self::$logs[] = new LogModel($dir,$catlog.'.log',$level,$time,$str);


    }

}